package com.ruoyi.aiworkflow.services.impl;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ruoyi.aiworkflow.services.ICozeWorkflow;
import com.ruoyi.aiworkflow.services.config.CozeWorkflowConfig;
import com.ruoyi.aiworkflow.services.dto.MbtiRules;
import com.ruoyi.aiworkflow.services.dto.QuestionsDTO;
import com.ruoyi.common.clients.CozeClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.MessageFormat;
import java.util.*;

@Service
public class CozrWorkflow implements ICozeWorkflow {

    @Autowired
    CozeWorkflowConfig cozeConfig;


    @Resource
    private CozeClient cozeClient;


    @Override
    public Map<String, Object> getJSON(String QueryJson) {
        Map<String, Object> map = new HashMap<>();
        if (QueryJson.equals("")) {
            return map;
        }
        //我的测试结果 ESTJ ，测试原始值：{\"E\":12,\"I\":0,\"S\":12,\"N\":0,\"T\":12,\"F\":0,\"J\":12,\"P\":0}"
        String content = cozeClient.sendRequest(cozeConfig.getBotId(), cozeConfig.getToken(), QueryJson);
        JSONObject jsonResponse = new JSONObject(content);

        // 获取messages数组
        JSONArray messages = jsonResponse.getJSONArray("messages");

        // 遍历messages查找type为"answer"的消息
        for (int i = 0; i < messages.size(); i++) {
            JSONObject message = messages.getJSONObject(i);
            if ("answer".equals(message.getStr("type"))) {
                // 获取content字段中的JSON字符串
                String contentStr = message.getStr("content");

                // 提取JSON部分（去除markdown代码块标记）
                if (contentStr.startsWith("```json")) {
                    contentStr = contentStr.substring(7); // 去掉开头的 ```json
                }
                if (contentStr.endsWith("```")) {
                    contentStr = contentStr.substring(0, contentStr.length() - 3); // 去掉结尾的 ```
                }
                // 去除首尾空白字符
                contentStr = contentStr.trim();

                return getJSONAsMap(contentStr);
            }
        }
        return map;
    }

    @Override
    public QuestionsDTO CreatTestQuestions(int Count, String subTitle) throws JsonProcessingException {
        Map<String, Object> map = new HashMap<>();
        QuestionsDTO questionsDTO = new QuestionsDTO();

        if (Count <= 0) {
            return questionsDTO;
        }
        String QueryJson = "";
        if (subTitle.equals("")) {
            QueryJson = "帮我生成一套 " + Count + " 题目的题库";
        } else {
            QueryJson = subTitle;
        }

        String content = cozeClient.sendRequest(cozeConfig.getTestquestionsBotId(), cozeConfig.getToken(), QueryJson);
        JSONObject jsonResponse = new JSONObject(content);

        // 获取messages数组
        JSONArray messages = jsonResponse.getJSONArray("messages");

        String contentStr = "";
        // 遍历messages查找type为"answer"的消息
        if (messages==null){
            return questionsDTO;
        }
        for (int i = 0; i < messages.size(); i++) {
            JSONObject message = messages.getJSONObject(i);
            if ("answer".equals(message.getStr("type"))) {
                // 获取content字段中的JSON字符串 
                contentStr = message.getStr("content");

                // 提取JSON部分（去除markdown代码块标记）
                if (contentStr.startsWith("```json")) {
                    contentStr = contentStr.substring(7); // 去掉开头的 ```json
                }
                if (contentStr.endsWith("```")) {
                    contentStr = contentStr.substring(0, contentStr.length() - 3); // 去掉结尾的 ```
                }
                // 去除首尾空白字符
                contentStr = contentStr.trim();

                //return getJSONAsMap(contentStr);
            }
        }
        //
        if (!contentStr.isEmpty()) {
            ObjectMapper mapper = new ObjectMapper();
            //map转对象
            QuestionsDTO dto = mapper.readValue(contentStr, QuestionsDTO.class);
            return dto;
        }
        return questionsDTO;
    }

    @Override
    public QuestionsDTO CreatTestQuestionsV2(int Count) throws JsonProcessingException {
        QuestionsDTO questionsDTO = new QuestionsDTO();

        if (Count <= 0) {
            return questionsDTO;
        }
        //计算当前总题目数，4个维度，每个维度有多少个题目
        int itemCount = Count / 4;
        String[] array = {"E/I", "S/N", "T/F", "J/P"};
        List<String> list = Arrays.asList(array);

        String SubTitle = "帮我生成一套 {0} 题目的题库";
        // 创建一个列表来存储所有题目
        List<com.ruoyi.aiworkflow.services.dto.MbtiQuestions> allQuestions = new ArrayList<>();
        MbtiRules combinedRules = null;
        long totalQuestionCount = 0;

        //维度 E/I（50 题）
        for (int i = 0; i < list.size(); i++) {
            String item = list.get(i);
            String CreateTitle = "维度 " + item + " (" + itemCount + "题)";
//            String format = String.format(SubTitle, CreateTitle);

//            String pattern = "尊敬的{0}，您购买了{1}个{2}。";
            MessageFormat messageFormat = new MessageFormat(SubTitle, Locale.CHINA);

            Object[] arguments = {CreateTitle};
            String resultMessage = messageFormat.format(arguments);

            QuestionsDTO questionsItem = CreatTestQuestions(itemCount, resultMessage);

            // 合并题目
            if (questionsItem != null && questionsItem.getQuestions() != null) {
                allQuestions.addAll(questionsItem.getQuestions());
                totalQuestionCount += questionsItem.getQuestion_count() != null ? questionsItem.getQuestion_count() : 0;

                // 如果还没有设置规则，则使用第一个规则
                if (combinedRules == null && questionsItem.getScoring_rules() != null) {
                    combinedRules = questionsItem.getScoring_rules();
                }
            }
        }

        // 设置最终的questionsDTO
        questionsDTO.setQuestions(allQuestions);
        questionsDTO.setQuestion_count(totalQuestionCount);
        questionsDTO.setScoring_rules(combinedRules);

        return questionsDTO;
    }


    /**
     * 将JSON字符串解析为Map<String, Object>
     *
     * @return 解析后的Map对象
     */
    public Map<String, Object> getJSONAsMap(String jsonStr) {
        if (jsonStr == null || jsonStr.isEmpty()) {
            return new HashMap<>();
        }

        try {
            // 将JSON字符串转换为Map<String, Object>
            JSONObject jsonObject = new JSONObject(jsonStr);
            Map<String, Object> resultMap = new HashMap<>();
            for (String key : jsonObject.keySet()) {
                resultMap.put(key, jsonObject.get(key));
            }

            return resultMap;
        } catch (Exception e) {
            // 如果解析失败，返回空Map
            return new HashMap<>();
        }
    }
}